import os

import pytest
import yaml
from config import settings
from common.client import ApiClient


def pytest_addoption(parser):
    """
    该钩子函数可以让用户注册一个自定义的命令行参数，以便于用户在测试开始前将数据从外部（如：控制台）传递给程序
    :param parser:
    :return:
    """
    parser.addoption("--env", default="test", help="测试环境配置", choices=["test", "prod"])


def pytest_configure(config):
    # 加载测试数据
    data_dir = os.path.join(settings.BASE_DIR, "testcases", "data")
    pytest.get_weather_cases = []

    for dirpath, dirnames, filenames in os.walk(str(data_dir)):
        for file in filenames:
            if file.endswith((".yaml", "yml")):
                file_path = os.path.join(dirpath, file)
                with open(file_path, "r", encoding="utf-8") as f:
                    test_data = yaml.safe_load(f) or []
                    pytest.get_weather_cases.extend(test_data)


@pytest.fixture(scope="session")
def api_client(request):
    """
    全局API客户端: 读取自定义命令行的env参数，根据参数值选择不同的环境配置
    :param request:
    :return:
    """
    env = request.config.getoption("--env")
    base_url = settings.ENV_CONFIG.get(env)
    return ApiClient(base_url)
